<template>
  <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px" class="demo-ruleForm">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="form.username" disabled></el-input>
    </el-form-item>
    <el-form-item label="用户昵称" prop="nickName">
      <el-input v-model="form.nickName"></el-input>
    </el-form-item>
    <el-form-item label="手机号码" prop="phone">
      <el-input v-model="form.phone"></el-input>
    </el-form-item>
    <el-form-item label="所属部门" prop="dept">
      <el-input v-model="form.dept"></el-input>
    </el-form-item>
    <el-form-item label="头像" prop="avatar">
      <el-upload
        class="avatar-uploader"
        action="https://jsonplaceholder.typicode.com/posts/"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="form.avatar" :src="form.avatar" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
          <plus />
        </el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">保 存</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { defineComponent, reactive, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'

export default defineComponent({
  components: { Plus },
  setup() {
    const rules = reactive()

    const store = useStore()
    const form = computed(() => store.getters.userInfo)
    console.log(form.value)
    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        ElMessage.error('Avatar picture must be JPG format!')
      }
      if (!isLt2M) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
      }
      return isJPG && isLt2M
    }
    const handleAvatarSuccess = (res, file) => {
      form.avatar = URL.createObjectURL(file.raw)
    }
    const submit = () => {
      ElMessage({
        message: '保存成功',
        type: 'success',
      })
    }
    return {
      rules,
      form,
      submit,
      beforeAvatarUpload,
      handleAvatarSuccess,
    }
  },
})
</script>
<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>